<template>
  <div class="listContent">
    <el-form :rules="rules" :label-position="labelPosition" label-width="140px">
      <el-form-item
        label="操作步骤："
        prop="operationStep"
        style="text-align: left"
      >
        <el-button
          class="btn-text-blue"
          size="mini"
          icon="el-icon-plus"
          @click="addRow"
          v-if="!isReadonly"
          >新建</el-button
        >
        <el-button
          class="btn-text-blue"
          size="mini"
          icon="el-icon-download"
          @click="downloadModel"
          v-if="!isReadonly"
          >下载导入模板</el-button
        >
        <el-button
          class="btn-text-blue"
          size="mini"
          icon="el-icon-download"
          @click="derive"
          >导出</el-button
        >

        <el-button
          class="btn-text-blue"
          size="mini"
          icon="el-icon-upload2"
          @click="uploadExcel"
          v-if="!isReadonly"
          >导入</el-button
        >

        <el-table
          :data="treetableData"
          style="width: 100%"
          row-key="sort"
          border
          :cell-style="tableCellStyle"
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :span-method="objectSpanMethod"
          :header-cell-class-name="starAdd"
        >
          <el-table-column
            prop="sort"
            label="序号"
            width="100"
            align="left"
          ></el-table-column>

          <el-table-column
            prop="dept"
            label="受令单位"
            align="center"
            width="180"
          >
            <template slot-scope="scp">
              <el-input
                size="mini"
                :disabled="isReadonly"
                readonly
                v-model="scp.row.deptName"
                v-if="[0].includes(status)"
              >
                <el-button
                  icon="el-icon-location"
                  slot="append"
                  :disabled="isReadonly"
                  @click="goSeleteOrgMember(scp.row.sort, 'dept', 'deptName')"
                ></el-button>
              </el-input>
              <input
                v-model="scp.row.deptName"
                :readonly="isReadonly"
                :class="['stepInput', { readText: isReadonly }]"
                v-if="[1, 2, 3, -1].includes(status)"
              />
            </template>
          </el-table-column>

          <el-table-column prop="item" label="操作项目" align="center">
            <template slot-scope="scp">
              <input
                v-model="scp.row.item"
                :readonly="isReadonly"
                :class="['stepInput', { readText: isReadonly }]"
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="publishTime"
            label="发令时间"
            align="center"
            width="150"
            v-if="[2, 3, -1].includes(status)"
          >
            <template slot-scope="scp">
              <el-date-picker
                v-model="scp.row.publishTime"
                size="mini"
                type="datetime"
                :sort="scp.row.sort"
                prop="publishTime"
                @focus="focusInput"
                @change="dateInputChange"
                placeholder="选择日期"
                align="left"
                clearable
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                v-if="[2].includes(status)"
              ></el-date-picker>
              <input
                v-model="scp.row.publishTime"
                :readonly="isReadonly"
                :class="['stepInput', { readText: isReadonly }]"
                v-if="[3, -1].includes(status)"
              />
            </template>
          </el-table-column>
          
          <el-table-column
            prop="acceptManName"
            label="受令人"
            align="center"
            width="150"
            v-if="[2, 3, -1].includes(status)"
          >
            <template slot-scope="scp">
              <el-input
                size="mini"
                readonly
                v-model="scp.row.acceptManName"
                v-if="[2].includes(status)"
              >
                <el-button
                  icon="el-icon-user"
                  slot="append"
                  @click="
                    goSeleteOrgMember(scp.row.sort, 'user', 'acceptManName')
                  "
                ></el-button>
              </el-input>
              <input
                v-model="scp.row.acceptManName"
                :readonly="isReadonly"
                :class="['stepInput', { readText: isReadonly }]"
                v-if="[3, -1].includes(status)"
              />
            </template>
          </el-table-column>

           <el-table-column
            prop="reportTime"
            label="完成时间"
            align="center"
            width="150"
            v-if="[2, 3, -1].includes(status)"
          >
            <template slot-scope="scp">
              <el-date-picker
                v-model="scp.row.reportTime"
                size="mini"
                type="datetime"
                :sort="scp.row.sort"
                prop="reportTime"
                @focus="focusInput"
                @change="dateInputChange"
                placeholder="选择日期"
                align="left"
                clearable
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                v-if="[2].includes(status)"
              ></el-date-picker>
              <input
                v-model="scp.row.reportTime"
                :readonly="isReadonly"
                :class="['stepInput', { readText: isReadonly }]"
                v-if="[3, -1].includes(status)"
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="reportManName"
            label="报告人"
            align="center"
            width="150"
            v-if="[2, 3, -1].includes(status)"
          >
            <template slot-scope="scp">
              <el-input
                size="mini"
                readonly
                v-model="scp.row.reportManName"
                v-if="[2].includes(status)"
              >
                <el-button
                  icon="el-icon-user"
                  slot="append"
                  @click="
                    goSeleteOrgMember(scp.row.sort, 'user', 'reportManName')
                  "
                ></el-button>
              </el-input>
              <input
                v-model="scp.row.reportManName"
                :readonly="isReadonly"
                :class="['stepInput', { readText: isReadonly }]"
                v-if="[3, -1].includes(status)"
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="marks"
            label="划号"
            align="center"
            width="60"
            v-if="[2, 3, -1].includes(status)"
          >
            <template slot-scope="scp">
              <el-checkbox
                v-model="scp.row.marks"
                v-if="[2].includes(status)"
                :true-label="1"
                :false-label="0"
                size="medium"
              ></el-checkbox>
              <el-checkbox
                v-model="scp.row.marks"
                :true-label="1"
                :false-label="0"
                :disabled="isReadonly"
                size="medium"
                v-if="[3, -1].includes(status)"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column
            prop="reportTime"
            label="备注"
            align="center"
            width="150"
            v-if="[2, 3, -1].includes(status)"
          >
            <template slot-scope="scp">
              <input
                v-model="scp.row.remarks"
                class="stepInput"
                v-if="[2].includes(status)"
              />
              <input
                v-model="scp.row.remarks"
                v-if="[3, -1].includes(status)"
                :readonly="isReadonly"
                :class="['stepInput', { readText: isReadonly }]"
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="operation"
            label="操作"
            width="180"
            align="center"
            v-if="!isReadonly"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="newChild(scope.row)"
                v-if="scope.row.children"
                >新建子项</el-button
              >
              <!-- 删除父项 -->
              <el-button
                type="text"
                @click="deleteStep(scope.row)"
                v-if="scope.row.children"
                >删除</el-button
              >
              <!-- 删除子项 -->
              <el-button
                type="text"
                @click="deleteChildStep(scope.row)"
                v-if="!scope.row.children"
                >删除</el-button
              >
              <el-button
                type="text"
                @click="moveUp(scope.row)"
                v-if="!scope.row.children"
                >上移</el-button
              >
              <el-button
                type="text"
                @click="moveDown(scope.row)"
                v-if="!scope.row.children"
                >下移</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <input
      type="file"
      ref="uploadFile"
      style="display: none"
      @change="autoUploadFile"
    />
    <!-- 选择单位的弹出层 -->
    <dialogPublic
      :title="'信息选择'"
      :show.sync="showMember"
      @doSubmit="addSeleteMember"
      @doClose="() => (showMember = false)"
      appendTobody
    >
      <orgMemberSelect
        ref="orgMemberSelect"
        v-if="showMember"
        :seleteSetting="orgMemberSelect"
      ></orgMemberSelect>
    </dialogPublic>
  </div>
</template>
<script>
import {
  uploadExcel,
  exportTreeStep,
} from "@/api/twoTicketManagement/operationTicket.js";
export default {
  props: {
    //主表ID
    ticketId: {
      type: String,
      default: "",
    },
    //列表数据
    formListData: {
      type: Array,
      default: () => [],
    },
    //列表是否为只读
    isReadonly: {
      type: Boolean,
      default: false,
    },
    status: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      labelPosition: "right",
      rules: {
        //operationStep: [{ required: true }],
      },
      //调度操作步骤
      treetableData: [],
      formData: null,
      basicConfig: {
        labelWidth: "0",
        itemArr: [
          {
            label: "",
            prop: "dept",
            type: "dept",
            required: true,
            span: 100,
          },
        ],
      },
      //选部门弹出层
      showMember: false,
      curSelectRow: null, //记录点击的是第几行的受令单位
      curSelectProp: null, //记录点击的字段
      orgMemberSelect: {},
    };
  },
  methods: {
    //设置头部样式
    headerCellStyle() {
      return {
        background: "#fafafa",
        color: "#333333",
      };
    },
    //设置td样式
    tableCellStyle() {
      return {
        "border-bottom": "1px solid #ebebeb",
        padding: "5px 0!important",
      };
    },
    //增加一行
    addRow() {
      let sort = this.treetableData.length + 1;
      this.treetableData.push({
        sort: sort,

        children: [
          {
            sort: Number(sort + "." + 1),
          },
        ],
      });
    },
    //增加一行子层级
    newChild(row) {
      this.treetableData.map((item) => {
        if (item.sort === row.sort) {
          //判段当前父级下是否有子级
          if (item.children.length !== 0) {
            const rNum =
              parseInt(
                item.children[item.children.length - 1].sort
                  .toString()
                  .split(".")[1]
              ) + 1;
            const sort = item.sort + "." + rNum;
            item.children.push({ sort });
          } else {
            const sort = Number(item.sort + "." + 1);
            item.children.push({ sort });
          }
        }
      });
    },
    //下载导入模板
    downloadModel() {
      this.$utils.downloadFile(
        null,
        null,
        "eam-service-ticket/operation/downExcelDetStepdetTemplate?type=2"
      );
    },
    //导出
    async derive() {
      if (this.treetableData.length !== 0) {
        const blob = await exportTreeStep(this.treetableData);
        let a = document.createElement("a");
        document.body.appendChild(a);
        a.href = window.URL.createObjectURL(new Blob([blob]));
        a.download = "操作步骤.xls";
        a.click();
        document.body.removeChild(a);
      }
    },
    //导入数据
    uploadExcel() {
      const fileObj = this.$refs.uploadFile;
      fileObj.click();
    },
    //自动上传附件并获取回传的数据
    autoUploadFile() {
      const fileObj = this.$refs.uploadFile.files[0];
      const formData = new FormData();
      formData.append("file", fileObj);
      formData.append("type", 2);

      //上传并接收回传的数据
      uploadExcel(formData).then((res) => {
        res.data.forEach((rowData) => {
          rowData.errorMsg &&
            this.$message({
              showClose: true,
              type: "error",
              message: `导入失败：第${rowData.sort}行，${rowData.errorMsg}`,
            });
        });
        //合并原有和导入的，并排序
        let orgin = this.treetableData
        if(this.treetableData.length===1){
            const child = this.treetableData[0].children
            let flag = true
            for(let i =0;i<child.length;i++){
              if((child[i].deptName!=="" || child[i].item!=="") && (child[i].deptName!==undefined || child[i].item!==undefined)){
                flag=false
              }
            }
            flag && (orgin=[])
        }
        const resArr = this.listDataSort([...orgin, ...res.data]);
        this.treetableData = resArr;
      });
    },

    //删除父层级步骤
    deleteStep(row) {
      //删掉数据
      let data = this.treetableData.filter((item) => item.sort != row.sort);
      //重新排序
      this.treetableData = this.listDataSort(data);
    },
    //删除子层级步骤
    deleteChildStep(row) {
      //删掉数据
      this.treetableData.filter((item) => {
        let arr = [];
        item.children.filter((child) => {
          if (child.sort != row.sort) {
            arr.push(child);
          }
        });
        item.children = arr;
      });
      //重新排序
      this.treetableData = this.listDataSort(this.treetableData);
    },
    //向上移动
    moveUp(row) {
      this.treetableData.filter((item) => {
        item.children.filter((child, index) => {
          if (child.sort === row.sort) {
            if (item.children[index - 1]) {
              [item.children[index], item.children[index - 1]] = [
                item.children[index - 1],
                item.children[index],
              ];
            } else {
              this.$message({
                showClose: true,
                message: "到顶啦！!",
              });
            }
          }
        });
      });
      //重新排序
      this.treetableData = this.listDataSort(this.treetableData);
    },
    //向下移动
    moveDown(row) {
      let indexs = {};
      this.treetableData.filter((item, n) => {
        item.children.filter((child, i) => {
          if (child.sort === row.sort) {
            indexs.parentRowNum = n;
            indexs.childRowNum = i;
          }
        });
      });
      const { parentRowNum, childRowNum } = indexs;
      if (this.treetableData[parentRowNum].children[childRowNum + 1]) {
        [
          this.treetableData[parentRowNum].children[childRowNum],
          this.treetableData[parentRowNum].children[childRowNum + 1],
        ] = [
          this.treetableData[parentRowNum].children[childRowNum + 1],
          this.treetableData[parentRowNum].children[childRowNum],
        ];
      } else {
        this.$message({
          showClose: true,
          message: "到底啦！!",
        });
      }

      //重新排序
      this.treetableData = this.listDataSort(this.treetableData);
    },
    //列表数据排序
    listDataSort(data) {
      //重新排序
      data.map((item, index) => {
        //重排父层级
        item.sort = index + 1;
        //重排子层级
        if (item.children) {
          item.children.map((obj, i) => {
            obj.sort = item.sort + "." + (i + 1);
          });
        }
      });
      return data;
    },

    //合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (row.children && [0, 1].includes(this.status)) {
        if (columnIndex === 0) {
          return [1, 3];
        } else if (columnIndex === 1) {
          return [0, 0];
        } else if (columnIndex === 2) {
          return [0, 0];
        } else if (columnIndex === 3) {
          return [1, 1];
        }
      }
      if (row.children && [2, 3, -1].includes(this.status)) {
        if (columnIndex === 0) {
          return [1, 9];
        } else {
          return [0, 0];
        }
      }
    },

    //选择组织
    goSeleteOrgMember(sort, type, prop) {
      this.showMember = true;
      this.curSelectRow = sort;
      this.curSelectProp = prop;
      //选部门
      if (type === "dept") {
        this.orgMemberSelect = {
          seleteType: "org",
          radio: true, //单选还是多选
          outOrg: 0, //是否是外单位
          props: {
            label: "name",
            children: "children",
          },
          column: [
            {
              label: "组织",
              prop: "name",
            },
          ],
          chosedData: [],
        };
      }
      //选人员
      if (type === "user") {
        this.orgMemberSelect = {
          seleteType: "orgmember",
          radio: true, //单选
          defaultOrgCode: "",
          props: {
            label: "name",
            children: "children",
          },
          column: [
            {
              label: "用户名",
              prop: "name",
              width: 60,
            },
            {
              label: "电话",
              prop: "phone",
              width: 100,
            },
          ],
          chosedData: [],
        };
      }
    },

    //确认选择
    addSeleteMember() {
      const data = this.$refs.orgMemberSelect.getSeleteData();
      this.treetableData.map((item) =>
        item.children.map((child) => {
          if (child.sort === this.curSelectRow) {
            child[this.curSelectProp] = data[0].name;
            child[this.curSelectProp.replace("Name", "")] = data[0].account;
          }
        })
      );
      //坑...不会自动响应，还要转一下才能触发渲染,$set都不管用
      const temp = JSON.stringify(this.treetableData);
      this.treetableData = JSON.parse(temp);
      this.showMember = false;
    },
    //日期
    dateInputChange(val) {
      this.treetableData.map((item) =>
        item.children.map((child) => {
          if (child.sort === this.curSelectRow) {
            child[this.curSelectProp] = val;
          }
        })
      );
    },
    //设置头部标*
    starAdd(obj) {
      if (
        [2, 3, -1].includes(this.status) &&
        ![0, 7, 8].includes(obj.columnIndex)
      ) {
        return "star";
      }
      if ([0].includes(this.status) && ![0, 3].includes(obj.columnIndex)) {
        return "star";
      }
    },
    //
    focusInput(val) {
      this.curSelectRow = val.$attrs.sort;
      this.curSelectProp = val.$attrs.prop;
      const flag = this.checkBeforeGrade();
      // if (flag) {
      //   this.curSelectProp = prop;
      //   this.curSelectRow = sort;
      // }
    },
    //检查前面层级是否有未填写的输入框
    checkBeforeGrade() {},
  },
  watch: {
    formListData: {
      handler(val) {
        //排序
        if (val.length !== 0) {
          const deepCopy = JSON.parse(JSON.stringify(val));
          for (let obj of deepCopy) {
            const { children } = obj;
            children.sort((a, b) => {
              let val1 = parseInt(a.sort.split(".")[1]);
              let val2 = parseInt(b.sort.split(".")[1]);
              if (val1 < val2) {
                return -1;
              } else if (val1 > val2) {
                return 1;
              } else {
                return 0;
              }
            });
          }
          this.treetableData = deepCopy;
        }
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="less" scoped>
.el-icon-delete,
.el-icon-caret-top,
.el-icon-caret-bottom {
  font-size: 20px;
  color: #2c77f4;
  cursor: pointer;
}
.stepInput {
  padding: 8px 10px;
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
  color: #606266;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.stepInput:focus {
  border: 1px solid #409eff;
}
.readText:focus,
.readText {
  border: 0;
  background-color: transparent;
}
/deep/table th.star .cell::before {
  content: " * ";
  color: red;
}
.listContent /deep/.el-date-editor{
  width: 125px!important;
}
</style>